<template>
  <div>
    <el-card class="question-detail-card">
      <!-- header -->
      <div class="question-detail-card-header">
        <el-avatar
          style="width: 50px; height: 50px"
          :src="avatarFullPath"
        ></el-avatar>
        <div
          style="
            display: flex;
            align-items: center;
            width: 235px;
            margin-left: 20px;
          "
        >
          <div style="margin-right: 10px; font-weight: bold">楼主</div>
          {{ userName }}
        </div>
        <div style="display: flex; align-items: center; margin-left: 320px">
          {{ formattedDate }}
        </div>
      </div>
      <!-- body -->
      <div class="question-detail-card-body">
        <h3>{{ artcleTitle }}</h3>
        <div class="question-detail-card-body-text">
          {{ articleText }}
        </div>
      </div>
      <!-- bottom -->
      <div class="question-detail-card-bottom">
        <div style="width: 550px">
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除吗？"
            @confirm="confirmDetele"
          >
            <i
              class="el-icon-delete delete-icon"
              v-if="showdelete"
              @click="deleteArticleById"
              slot="reference"
            >
              删除</i
            >
          </el-popconfirm>
        </div>
        <div class="action-item" style="width: 110px" @click="operateZan">
          <i :class="zanIcon"></i> 有用 {{ formattedLikeCount }}
        </div>
        <div class="action-item" style="width: 70px" @click="reply">
          <i class="el-icon-chat-dot-square"></i> 评论
        </div>
      </div>
    </el-card>
    <!-- 下面是回复的卡片 -->
    <div v-for="reply in replyList" :key="reply.replyid">
      <AnswerCard
        :replyId="reply.replyid"
        :answerId="reply.receiveid"
        :answerText="reply.replycontent"
        :artcleId="reply.articleid"
        :createDate="reply.createtime"
        :userId="reply.userid"
        @getReplyListByArticleId="getReplyListByArticleId"
      ></AnswerCard>
    </div>
    <!-- 加上v-if确保userId，userName，artcleId都已拿到-->
    <AnswerDrawer
      v-if="userId && userName && artcleId"
      ref="answerDrawer"
      :artcleId="artcleId"
      :userId="userId"
      :userName="userName"
      @getReplyListByArticleId="getReplyListByArticleId"
    ></AnswerDrawer>
  </div>
</template>

<script>
import AnswerDrawer from "./AnswerDrawer.vue";
import AnswerCard from "./AnswerCard.vue";

export default {
  created() {
    this.init();
  },
  components: {
    AnswerCard,
    AnswerDrawer,
  },
  data() {
    return {
      //根据用户Id和文章Id来确定该卡片的数据
      userId: "", //用户Id
      userName: "", //用户名
      artcleId: "", //文章Id
      artcleTitle: "", //文章标题
      articleText: "", //文章内容
      likeCount: 0, //点赞数
      commentCount: 0, //评论数
      createDate: "", //创建日期，
      zanIcon: "el-icon-ali-weidianzan", //点赞图标
      avatar: "", //图片名称
      avatarFullPath: "", //图片地址
      replyList: [], //回复列表
    };
  },
  methods: {
    //点赞或者取消赞
    operateZan() {
      if (this.zanIcon == "el-icon-ali-weidianzan") {
        this.zanIcon = "el-icon-ali-yidianzan";
        this.likeCount++;
        this.addOrUpdateArticleLikeRecordByUserIdAndArticleId();
      } else {
        this.zanIcon = "el-icon-ali-weidianzan";
        this.likeCount--;
        this.addOrUpdateArticleLikeRecordByUserIdAndArticleId();
      }
    },
    //回复消息
    reply() {
      this.$refs.answerDrawer.$data.drawer = true;
    },
    //初始化文章信息
    init() {
      //从路由中拿到用户id和文章id从而得到其他数据
      console.log(this.$route.params);
      this.userId = this.$route.params.userId;
      this.artcleId = this.$route.params.artcleId;

      this.getAirticleById();
      this.getUserInfoById();
      this.getReplyListByArticleId();
      this.getLikeCountByArticleId();
      this.getIsLikeByUserIdAndArticleId();
    },
    //根据文章id获取文章信息
    getAirticleById() {
      this.$request.getHttp({
        url: "/article/getArticleById",
        params: {
          articleId: this.artcleId,
        },
        success: (data) => {
          this.artcleTitle = data.article.articletitle;
          this.articleText = data.article.articlecontent;
          this.likeCount = data.article.likecount;
          this.commentCount = data.article.replycount;
          this.createDate = data.article.createtime;
        },
        error: (error) => {},
      });
    },
    //根据userId获取用户名和头像
    getUserInfoById() {
      this.$request.getHttp({
        url: "/user/getUserInfoById",
        params: {
          userId: this.userId,
        },
        success: (data) => {
          if (data.code == 200) {
            this.userName = data.user.username;
            this.avatar = data.user.avatar;
            this.avatarFullPath = `${this.$store.state.ipAddr}/${this.avatar}`;
          }
        },
        error: (error) => {},
      });
    },
    //根据文章id获取回复列表
    getReplyListByArticleId() {
      this.$request.getHttp({
        url: "/reply/getReplyListByArticleId",
        params: {
          articleId: this.artcleId,
        },
        success: (data) => {
          this.replyList = data.list;
        },
        error: (error) => {},
      });
    },
    //确认删除文章
    confirmDetele() {
      this.deleteArticleById();
    },
    //根据文章id删除当前文章
    deleteArticleById() {
      console.log("deleteArticleById");
      this.$request.postHttp({
        url: "/article/deleteArticleById",
        params: {
          articleId: this.artcleId,
        },
        success: (data) => {
          console.log(data);
          if (data.isDelete) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.$router.back();
          }
        },
        error: (error) => {
          this.$message({
            message: "删除失败",
            type: "error",
          });
          console.log(error);
        },
      });
    },
    //获取文章的点赞数
    getLikeCountByArticleId() {
      this.$request.getHttp({
        url: "/articlelikerecord/getLikeCountByArticleId",
        params: {
          articleId: this.artcleId,
        },
        success: (data) => {
          if (data.code == 200) {
            this.likeCount = data.likeCount;
          }
        },
        error: (error) => {},
      });
    },
    //获取当前用户是否点赞
    getIsLikeByUserIdAndArticleId() {
      let d = {
        userid: localStorage.getItem("userId"),
        articleid: this.artcleId,
      };
      console.log(d);
      this.$request.postHttp({
        url: "/articlelikerecord/getIsLikeByUserIdAndArticleId",
        data: d,
        success: (data) => {
          console.log("xxxxx", data);
          if (data.isLike) {
            this.zanIcon = "el-icon-ali-yidianzan";
          }
        },
        error: (error) => {},
      });
    },
    //根据用户id和文章id添加或更新记录
    addOrUpdateArticleLikeRecordByUserIdAndArticleId() {
      this.$request.postHttp({
        url: "/articlelikerecord/addOrUpdateArticleLikeRecordByUserIdAndArticleId",
        data: {
          userid: localStorage.getItem("userId"),
          articleid: this.artcleId,
        },
        success: (data) => {
          console.log(data);
        },
        error: (error) => {},
      });
    },
  },
  computed: {
    //显示delete按钮
    showdelete() {
      //当前用户iD和文章的用户id相等
      return localStorage.getItem("userId") == this.userId;
    },
    //显示articleText的信息
    showText() {
      if (this.articleText.length < 300) return this.articleText;
      else {
        return this.articleText.substring(0, 300) + "...";
      }
    },
    formattedLikeCount() {
      const likeCount = this.likeCount;

      if (likeCount < 10000) {
        // 当数字小于5位数时，返回当前数字，并用空格填充到4位
        return likeCount;
      } else {
        // 当数字大于5位数时，转换成w表示法，并用空格填充到4位
        const formattedLikeCount = (likeCount / 10000).toFixed(1);
        return `${formattedLikeCount}w`.padStart(4, " ");
      }
    },
    formattedCommentCount() {
      const commentCount = this.commentCount;

      if (commentCount < 10000) {
        // 当数字小于5位数时，返回当前数字，并用空格填充到4位
        return commentCount;
      } else {
        // 当数字大于5位数时，转换成w表示法，并用空格填充到4位
        const formattedCommentCount = (commentCount / 10000).toFixed(1);
        return `${formattedCommentCount}w`.padStart(4, " ");
      }
    },
    formattedDate() {
      const today = new Date(this.createDate);
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
      const day = String(today.getDate()).padStart(2, "0");
      const formattedDate = `${year}-${month}-${day}`;
      return formattedDate;
    },
  },
};
</script>

<style scoped>
.question-detail-card {
  width: 780px;
  margin-bottom: 20px;
}
.question-detail-card-header {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.question-detail-card-body {
  margin-top: 10px;
  margin-left: 35px;
  width: 680px;
  min-height: 250px; /* 添加这一行来设置最小高度 */
}

.question-detail-card-bottom {
  display: flex;
  align-items: center;

  margin-top: 30px;
  margin-bottom: 10px;
}

.delete-icon {
  padding-left: 35px;
  cursor: pointer;
}

.action-item {
  cursor: pointer;
}

/* Additional styling for the hover effect */
.action-item:hover {
  background-color: #f0f0f0; /* Change the background color on hover */
}
</style>